<template>
  <div>
    <div style="height: 10px">
      <strong style="display: block; text-align: center; font-size: 40px"
      >雷暴大风识别</strong
      >
    </div>
    <div className="hello">
      <div className="box">
        <div className="chart">
          <div id="charts" ref="chart"></div>
        </div>
      </div>
    </div>
    <div class="time-picker-fixed">
      <div class="time-picker">
        <input type="date" v-model="selectedDate" id="dateInput" class="custom-input"  :min="'2023-08-01'" :max="'2023-09-07'">
        <select v-model="selectedHour" id="hourSelect" class="custom-input">
          <option v-for="hour in presetHours" :value="hour">{{ String(hour).padStart(2, '0') }}</option>
        </select>

        <select v-model="selectedMinute" id="minuteSelect" class="custom-input">
          <option v-for="minute in presetMinutes" :value="minute">{{ String(minute).padStart(2, '0') }}</option>
        </select>
        <button @click="fetchData" class="custom-button">获取数据</button>
      </div>
    </div>
  </div>
</template>

<script>
import {useStore} from "vuex";
import * as echarts from "echarts";
import 'echarts-gl';
import 'echarts/map/js/province/guangdong';
import 'echarts-extension-amap'
import {onMounted, onUnmounted, reactive, ref} from "vue";
import geoJson from '../assets/yuegangao.json';
import regionStylesData from '../assets/regionStyles.json';
import {getrecognitionData} from "../api/user/recognition";

export default {
  data() {
    return {
      presetHours: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
      presetMinutes: [0, 6, 12, 18, 24, 30, 36, 42, 48, 54],
    };
  },
  name: "Rectangle",
  components: {},
  setup() {
    const store = useStore()
    let myEcharts = echarts;
    let chart = null;
    let object = {
      user_id: store.state.userinfo.id,
      nums: 10
    }
    let selectedDate = ref('2023-08-01');
    let selectedHour = ref('3');
    let selectedMinute = ref('42');
    let selectedTime = ref('03:42');

    let arrayData = reactive({
      arrData: []
    });
    let cooData = ref([])

    let params = {
      year: 2023,
      month: 8,
      day: 1,
      hour: 3,
      minute: 42
    };

    onMounted(() => {
      initChart();
    });
    onUnmounted(() => {
      myEcharts.dispose;
      chart.dispose();
      chart = null;
    });

    async function initChart() {

      let COLORS = ['green', 'yellow', 'orange']

      let StartLat = 27.0
      let StartLon = 108.5
      let XReso = 0.01
      let YReso = 0.01

      cooData = await fetchCOOData(params);
      arrayData.arrData = await updateArrayData()

      let data = []
      for (const item of arrayData.arrData) {
        const lon = StartLon + item[1] * XReso
        const lat = StartLat - item[0] * YReso
        data.push([lon, lat, item[2]])
      }

      const guangdongCenter = [113.280637, 23.125178];
      chart = myEcharts.init(document.getElementById("charts"), "purple-passion");
      // 注册可用的地图
      myEcharts.registerMap('guangdong', geoJson);
      // 设置echarts的option
      await loadRegionStyles(chart);//突出大湾区线条
      chart.setOption({
        tooltip: {
          show: true,
          trigger: 'item',
          alwaysShowContent: false,
        },
        visualMap: {
          type: 'piecewise',
          inverse: false,
          bottom: '2%',
          right: '1%',
          pieces: [
            {
              min: 0,
              max: 0.5,
              color: 'green',
              label: '0-0.5'
            },
            {
              min: 0.5,
              max: 0.8,
              color: 'yellow',
              label: '0.5-0.8'
            },
            {
              min: 0.8,
              max: 1,
              color: 'orange',
              label: '0.8-1'
            },
          ],
          borderColor: '#ccc',
          borderWidth: 2,
          backgroundColor: '#eee',
          dimension: 3,
          inRange: {
            opacity: 0.7
          }
        },
        geo: {
          map: 'guangdong',
          center: guangdongCenter,//地图中心
          aspectScale: 1, //长宽比
          zoom: 7,
          roam: true,

          itemStyle: {
            normal: {
              borderColor: '#f4f4f4',
              areaColor: '#fff',
              shadowColor: '#182f68',
              shadowOffsetX: 0,
              shadowOffsetY: 1,
            },
            emphasis: {
              areaColor: '#2AB8FF',
              borderWidth: 0,
              label: {
                show: false
              }
            }
          },
          scaleLimit:{
            min:5,                          //最小的缩放值
            max:30,                            //最大的缩放值
          }
        },
        series: [
          {
            coordinateSystem: 'geo',
            type: 'custom',
            renderItem: function (params, api) {
              const position = api.coord([api.value(0), api.value(1)]);
              // 同步缩放
              const size = 12.5 * chart.getModel().getOption().geo[0].zoom / 7.0; // 正方形大小
              function getColorByValue() {
                if (api.value(2) >= 0.8) {
                  return 'orange';
                } else if (api.value(2) >= 0.5) {
                  return 'yellow';
                } else {
                  return 'green';
                }
              }

              // 根据每个点的值确定对应的颜色
              const color = getColorByValue();
              return new echarts.graphic.Rect({
                shape: {
                  x: position[0] - size / 2,
                  y: position[1] - size / 2,
                  width: size,
                  height: size,
                },
                style: {
                  fill: 'none',
                  // 需要动态决定方框的颜色
                  stroke: color,
                  lineWidth: 2.5 * chart.getModel().getOption().geo[0].zoom / 7.0,
                },
              });
            },
            encode: {
              tooltip: 2
            },
            data: data,
            tooltip: {
              formatter: function (params) {
                return params.value[2];
              }
            }
          },
        ],
      });
      window.onresize = function () {
        chart.resize();
      };
    }

    async function loadRegionStyles(chart) {
      try {
        // 使用导入的 JSON 数据
        const regionStyles = regionStylesData;
        chart.setOption({
          geo: {
            regions: regionStyles.regions,
          },
        });
      } catch (error) {
        console.error('Error loading region styles:', error);
      }
    }

    async function fetchCOOData(params) {
      try {
        let cooData1 = await getrecognitionData(params); // 使用接口文件中的函数获取数据
        return cooData1
      } catch (error) {
        console.error('Error fetching COO data:', error);
        showTopMessage('当前时间没有相关数据', 2000);
      }
    }

    async function updateArrayData() {
      // 遍历arrayData.arrData中的每个子数组
      let array = cooData.map(item => item.coo);
      // array[0]是一个二维数组
      return array[0]
    }

    function fetchData() {
      const selectedDateTime = `${selectedDate.value}T${String(selectedHour.value).padStart(2, '0')}:${String(selectedMinute.value).padStart(2, '0')}:00`;
      params = {
        year: new Date(selectedDateTime).getFullYear(),
        month: new Date(selectedDateTime).getMonth() + 1,
        day: new Date(selectedDateTime).getDate(),
        hour: new Date(selectedDateTime).getHours(),
        minute: new Date(selectedDateTime).getMinutes()
      };
      initChart();
    }


    function showTopMessage(message, duration) {
      // 创建一个提示元素
      const messageElement = document.createElement('div');
      messageElement.className = 'top-message';
      messageElement.textContent = message;

      // 将提示元素添加到页面的顶部
      document.body.appendChild(messageElement);

      // 设置定时器，在一定时间后自动隐藏提示
      setTimeout(() => {
        messageElement.style.opacity = '0'; // 渐变消失
        setTimeout(() => {
          document.body.removeChild(messageElement); // 删除提示元素
        }, 1000); // 在渐变结束后删除元素
      }, duration);

      // 自定义样式
      messageElement.style.position = 'fixed';
      messageElement.style.top = '100px';
      messageElement.style.left = '42%';
      messageElement.style.width = '300px';
      messageElement.style.borderRadius = '4px';
      messageElement.style.backgroundColor = '#88bffa';
      messageElement.style.color = '#fff';
      messageElement.style.padding = '10px 0';
      messageElement.style.textAlign = 'center';
      messageElement.style.transition = 'opacity 1s ease-in-out';
    }


    return {
      arrayData,
      selectedDate,
      selectedTime,
      fetchData,
      cooData,
      selectedHour,
      selectedMinute
    }
  }
}
</script>

<style scoped lang="scss">
.time-picker-fixed {
  position: fixed;
  top: 90%; /* 垂直居中 */
  left: 50%; /* 水平居中 */
  transform: translate(-50%, -50%); /* 居中偏移 */
  width: 1200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  background-color: transparent;
}

.time-picker {
  justify-content: center;
  width: 400px;
  display: flex;
  flex-direction: row; /* 水平布局 */
  align-items: center;
  border: 3px solid #007bff;
  padding: 20px;
  border-radius: 8px;
  background-color: #f0f0f0;
}

.head-name {
  color: #b0e3ff;
  font-weight: bold;
  font-size: xx-large;
  padding: 50px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}


@media screen and (min-width: 700px) {
  .chart {
    border: 3px double #c7e8ff;
    background-color: #6c8fff;
    margin: 60px;
    width: 70%;
    height: 65vh;

    #charts {
      width: 100%;
      height: 65vh
    }
  }
}


.custom-input {
  padding: 8px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.custom-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.custom-button:hover {
  background-color: #0056b3;
}

</style>
